# main.ps1
# Used to detect sudden power loss and shut down the server

param (
    [string]$CHK_IP
)

function Is-Health {
    param (
        [string]$ip_addr
    )

    $n = 0
    while ($true) {
        $pingResult = Test-Connection -ComputerName $ip_addr -Count 3 -Quiet
        if (-not $pingResult) {
            $timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
            "[ERROR]: 记录第${n}次不健康" | Out-File -FilePath "error.log" -Append
            $n++
        }
        else {
            # If ping is successful
            $n = 0
            return $true  # Return health flag
        }

        if ($n -gt 3) {
            return $false
        }

        Start-Sleep -Seconds 30  # Check every 30 seconds
    }
}

Start-Sleep -Seconds 600   # 停止10分钟后开始


$flg = 0
while ($true) {
    if (Is-Health -ip_addr $CHK_IP) {
        $timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
        "[INFO]: 健康" | Out-File -FilePath "info.log" -Append
    }
    else {
        $timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
        "[ERROR]: 不健康, 可能是对方已经断电了，现在要进行关机" | Out-File -FilePath "error.log" -Append
        $timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
        "[ERROR]: 现在等待10分钟，就关机" | Out-File -FilePath "error.log" -Append

        # Within 10 minutes, continuously check the health status of the detected IP
        # If healthy, cancel the shutdown command after 10 minutes
        for ($i = 0; $i -lt 10; $i++) {
            $pingResult = Test-Connection -ComputerName $CHK_IP -Count 3 -Quiet
            if ($pingResult) {
                $flg = 1
                break
            }
            Start-Sleep -Seconds 60
        }

        if ($flg -eq 1) {
            $flg = 0
            continue
        }

        # Shutdown-Computer -Force  # Shutdown, currently commented out
        $timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
        "[ERROR]: init 0" | Out-File -FilePath "error.log" -Append
        Stop-Computer
        break
    }

    Start-Sleep -Seconds 30
}
